/*在书中有关折半查找的例子中, while循环语句内共执行了两次测试
其实只要一次就足够(代价是将更多的测试在循环外执行).
重写该函数,使得在循环内部只执行一次测试.比较两种版本的函数的运行时间.
*/
#include <stdio.h>

int binsearch2(int x, int v[], int n);

int main(void)
{
    int v[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int x = 3;
    int len = sizeof(v) / sizeof(v[0]);
    int result = binsearch2(x, v, len);

    printf("%d\n", result);
    
    return 0;
}

int binsearch2(int x, int v[], int n)
{
    int low = 0;
    int high = n - 1;
    int mid = (low + high) / 2;

    while (low <= high && v[mid] != x)
    {
        mid = (low + high) / 2;
        if (v[mid] > x)
        {
            high = mid - 1;
        }
        else
        {
            low = mid + 1;
        }
    }
    if (low <= high)
    {
        return mid;
    }
    else
    {
        return -1;
    }
}